# 设置控制台编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "启动唐诗学习应用开发环境" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

Write-Host "正在检查并清理端口占用..." -ForegroundColor Green
Write-Host ""

# 函数：杀掉占用指定端口的进程
function Kill-PortProcess {
    param([int]$Port)
    
    try {
        $processes = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue
        if ($processes) {
            Write-Host "发现端口$Port被占用，正在清理..." -ForegroundColor Yellow
            foreach ($process in $processes) {
                $processId = $process.OwningProcess
                $processName = (Get-Process -Id $processId -ErrorAction SilentlyContinue).ProcessName
                Write-Host "正在终止进程 PID: $($processId) ($($processName))" -ForegroundColor Red
                Stop-Process -Id $processId -Force -ErrorAction SilentlyContinue
            }
            Write-Host "端口$Port已清理" -ForegroundColor Green
        } else {
            Write-Host "端口$Port未被占用" -ForegroundColor Gray
        }
    } catch {
        Write-Host "清理端口$Port时出错: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 清理端口3000和3001
Kill-PortProcess -Port 3000
Write-Host ""
Kill-PortProcess -Port 3001

Write-Host ""
Write-Host "等待端口释放..." -ForegroundColor Gray
Start-Sleep -Seconds 2

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "端口清理完成，正在启动开发环境..." -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "正在启动前端和后端服务..." -ForegroundColor Green
Write-Host "前端地址: http://localhost:3000" -ForegroundColor White
Write-Host "后端地址: http://localhost:3001" -ForegroundColor White
Write-Host ""
Write-Host "按 Ctrl+C 停止所有服务" -ForegroundColor Red
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

try {
    npm run dev:full
}
catch {
    Write-Host "启动失败，请检查错误信息" -ForegroundColor Red
    Write-Host "错误信息: $($_.Exception.Message)" -ForegroundColor Red
}

Write-Host ""
Write-Host "按任意键退出..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 